#include "stdafx.h"
#include <assert.h>
#include <xwt/xwt_dialog.h>

#ifdef WIN32
extern HINSTANCE _hAppInstance;
#endif

xwt::Dialog::Dialog (int resourceId) {
	m_resourceId = resourceId;
	m_flagModal = FALSE;
	m_pParent = NULL;

	Window::m_isDialog = TRUE;
}

xwt::DLG_RET xwt::Dialog::ShowModal (Window *pParent) {
	m_flagModal = TRUE;
	m_pParent = pParent;

	return ::DialogBoxParam (_hAppInstance, MAKEINTRESOURCE(m_resourceId),
								pParent ? pParent->GetHandle() : NULL,
								(DLGPROC)Window::_dlgProc, 
								(LPARAM) this );	
}

void xwt::Dialog::ShowModalLess (Window *pParent) {
	if (GetHandle() == NULL) {
		m_flagModal = FALSE;
		m_pParent = pParent;
		::CreateDialogParam ( _hAppInstance, MAKEINTRESOURCE(m_resourceId),
									pParent ? pParent->GetHandle() : NULL, 
									(DLGPROC)_dlgProc, (LPARAM) this );
	}
}

void xwt::Dialog::CloseDialog (DLG_RET result) {
	if (IsModal()) {
		::EndDialog (GetHandle(), result);
	} else {
		::DestroyWindow (GetHandle());
	}
}

void xwt::Dialog::SetControlText (int id, const sys_tchar *lpszText) {
	XWT_ASSERT (
		::SetDlgItemText (GetHandle(), id, lpszText)
		);
}

void xwt::Dialog::GetControlText (int id, sys_tchar *lpszBuff, size_t maxLength) {
	XWT_ASSERT (
		GetDlgItemText (GetHandle(), id, lpszBuff, maxLength)
		);
}

void xwt::Dialog::CenterDialog () {
	HWND hWndParent = NULL;

	if (m_pParent) hWndParent = m_pParent->GetHandle();
	if (!hWndParent) hWndParent = ::GetDesktopWindow ();

	if (hWndParent) {
		RECT rectDlg, rectParent;
		::GetWindowRect ( GetHandle(), &rectDlg );
		::GetWindowRect ( hWndParent, &rectParent );

		POINT offset = {
			rectParent.left + (rectParent.right - rectParent.left) / 2 - (rectDlg.right - rectDlg.left) / 2,
			rectParent.top + (rectParent.bottom - rectParent.top) / 2 - (rectDlg.bottom - rectDlg.top) / 2
		};

		::MoveWindow ( GetHandle(), offset.x, offset.y, rectDlg.right - rectDlg.left,
						rectDlg.bottom - rectDlg.top, 
						IsVisible() ? TRUE : FALSE
						);
	}
}

// message handlers...

void xwt::Dialog::OnCommand (int cmdId) {
	if (cmdId == IDOK) {
		OnOkButton ();
	} else if (cmdId == IDCANCEL) {
		OnCancelButton ();
	} else {
		xwt::Window::OnCommand (cmdId);
	}
}

void xwt::Dialog::OnInitDialog () {	
#ifdef XWT_DIALOG_USE_TRANSPARENCY
	// Set WS_EX_LAYERED on this window 

	SetWindowLong (GetHandle(), 
					GWL_EXSTYLE, 
					GetWindowLong(GetHandle(), GWL_EXSTYLE) | WS_EX_LAYERED
					);

	// Make this window 70% alpha
	SetLayeredWindowAttributes (GetHandle(), 0, (255 * 50) / 100, LWA_ALPHA);

#endif /* XWT_DIALOG_USE_TRANSPARENCY */

	CenterDialog ();

	if (!IsModal() && !IsVisible()) {
		Show ();
		Update ();
	}
}

void xwt::Dialog::OnOkButton () {
#ifdef WIN32
	CloseDialog (IDOK);
#endif
}

void xwt::Dialog::OnCancelButton () {
#ifdef WIN32
	CloseDialog (IDCLOSE);
#endif
}
